package jwtToken

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

/**
 * Created with Goland.
 * User: 令狐飞侠
 * Date: 2021-12-9
 * Description: jwt
 */

const (
	KEY = "I love go!"
)

// 根据用户名称生成jwt token
func GenerateJwtToken(userName string) (string, error) {

	//---------设置AccessToken------------------
	//1 生成claims
	acclaims := jwt.StandardClaims{
			ExpiresAt: time.Now().Add(30 * time.Second).Unix(),
			Issuer:    userName,
	}

	//2 生成token
	//token := jwt.NewWithClaims(jwt.SigningMethodES256, acclaims)
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, acclaims)

	// 3 签名
	signedToken, err := token.SignedString([]byte(KEY))
	if err != nil {
		fmt.Println("generate jwt token error:", err.Error())
		return "",err

	}

	return signedToken,nil
}

// 验证jwt token，返回用户名
func ParseJwtToken(signedToken string) (string, error){
	//1 解析 token
	token, err := jwt.Parse(signedToken, func(token *jwt.Token) (interface{}, error) {
		return []byte(KEY), nil
	})
	if err != nil {
		fmt.Println("parse jwt token error:", err.Error())
		if err, ok := err.(*jwt.ValidationError); ok {
			if err.Errors&jwt.ValidationErrorMalformed != 0 {
				fmt.Println(err.Error())
				return "",err
			}
			if err.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
				fmt.Println(err.Error())
				return "",err
			}
		}

	}
	// 2 获取 Claims
	mapClaims := token.Claims.(jwt.MapClaims)
	// 3 Claims获取userName
	var name = mapClaims["iss"].(string)
	return name,nil
}
